import axios from 'axios'
import type {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios'
import {ElMessage} from 'element-plus'

const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_API_BASE_URL,
    timeout: 15000,
})

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem("token")
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
            config.headers['token'] = `${token}`;
        }
        return config
    },
    (error) => {
        console.error('Request error:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data
        if (res.code !== 200) {
            ElMessage.error(res.message || 'Error')
            if (res.code === 401) {
                // Token 过期或无效，重定向到登录页
                localStorage.removeItem("token")
                window.location.href = '/login'
            }
            return Promise.reject(new Error(res.message || 'Error'))
        }
        return res
    },
    (error) => {
        console.error('Response error:', error)
        ElMessage.error(error.message || 'Request failed')
        return Promise.reject(error)
    }
)

export default service
